<?php

class m_users extends CI_Model{
	
	function _list($data){
		extract($data);
		$sql = "SELECT 
					user_name,
					user_passwd,
					user_login,
					user_logout,
					user_log,
					user_groups,
					group_name,
					user_id
				FROM s_users
					LEFT JOIN s_usergroups ON group_id = user_groups
				WHERE 
					users_sys_active = '1'
		";
		
		if (@$user_name != "") $sql .= " AND user_name like '%".@$user_name."%'";
		if (@$user_passwd != "") $sql .= " AND user_passwd like '%".@$user_passwd."%'";
		if (@$user_login != "") $sql .= " AND user_login like '%".@$user_login."%'";
		if (@$user_logout != "") $sql .= " AND user_logout like '%".@$user_logout."%'";
		if (@$user_log != "") $sql .= " AND user_log like '%".@$user_log."%'";
		if (@$user_groups != "") $sql .= " AND user_groups like '%".@$user_groups."%'";
		
		$query = $this->db->query($sql);
		$records = $query->num_rows();
		
		$sql = "SELECT * FROM (".$sql.") k LIMIT ".(($page - 1) * $rows).",".$rows;
		$query = $this->db->query($sql);
		$result = $query->result();
		
		return '{ 
		  "total": "'.ceil($records / $rows).'", 
		  "page": "'.$page.'", 
		  "records": "'.$records .'",
		  "rows" : '.json_encode($result).'
		}';
	}
	
	function _insert($data){
		$this->db->insert('s_users',$data);
		return 1;
	}
	
	function _update($data,$id){
		$this->db->where('user_id',$id);
		$this->db->update('s_users',$data);
		return 1;
	}
	
	function _delete($data,$id){
		$this->db->where('user_id',$id);
		$this->db->update('s_users',$data);
		return 1;
	}
	
	function s_usergroups(){
		$sql = "SELECT group_id, group_name FROM s_usergroups WHERE usergroups_sys_active = 1";
		$query = $this->db->query($sql);
		$data = array("");
		foreach($query->result() as $row){
			$data[$row->group_id] = $row->group_name;
		}
		return $data;
	}
}